import {ElMessage} from 'element-plus'

export function parseTime(time, cFormat) {
    if (arguments.length === 0) {
        return null
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
        date = time
    } else {
        if (('' + time).length === 10) time = parseInt(time) * 1000
        date = new Date(time)
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    }
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key]
        if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
        if (result.length > 0 && value < 10) {
            value = '0' + value
        }
        return value || 0
    })
    return time_str
}

/**
 * 获取url的全部参数
 */
export function getQueryObject(url) {
    url = url == null ? window.location.href : url
    const search = url.substring(url.lastIndexOf('?') + 1)
    const obj = {}
    const reg = /([^?&=]+)=([^?&=]*)/g
    search.replace(reg, (rs, $1, $2) => {
        const name = decodeURIComponent($1)
        let val = decodeURIComponent($2)
        val = String(val)
        obj[name] = val
        return rs
    })
    return obj
}

/**
 * 获取url参数
 */
export function getQueryParam(key) {
    return getQueryObject()[key]
}

/**
 * 获取缓存的值——String类型
 * return  返回获取的值，无返回空
 * 2022-07-21
 * */
export function getLocalStorageStr(key) {
    const val = localStorage.getItem(key)
    return val != undefined && val != null && val ? val : null
}

/**
 * 获取缓存的值——Object类型
 * return 返回JSON对象，否则返回空对象
 * 2022-07-21
 * */
export function getLocalStorageObject(key) {
    const val = localStorage.getItem(key)
    return val != undefined && val != 'undefined' && val != null && val ? JSON.parse(val) : null
}


